﻿using cn.jpush.api;
using cn.jpush.api.push.mode;
using Dapper;
using DapperExtensions;
using KD.Service.HR.Utility;
using Logistics.Model;
using Logistics.Model.QueryModel;
using Logistics.Model.Response;
using Logistics.Service;
using Logistics.Utility;
using Logistics.WebApi.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

namespace Logistics.WebApi.Controllers
{
    public class AutoBidController : ApiController
    {
        private BidBaseService bidService = new BidBaseService();
        private BidWLPriceService piceservice = new BidWLPriceService();
        private AndroidTokenService androidService = new AndroidTokenService();
        private CompushBaseService compushService = new CompushBaseService();
        /// <summary>
        /// 竟标开始
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ResponseModel GetAutoStartBillList()
        {
            var resultmod = new ResponseModel();

            int timenum = DateConvert.DateTimeToStamp(DateTime.Now);
            var bidlist = bidService.GetAutoStartBidList(timenum);
            foreach (wuliu_bid_base mod in bidlist)
            {
                wuliu_bid_base enty = new wuliu_bid_base();
                enty.state = 10;
                enty.bid_id = mod.bid_id;
                var fla= bidService.BidBaseUpdate(enty);
                if(fla>0)
                {
                    var list = androidService.GetCompanyidAndroidToken((int)mod.company_id);
                    foreach (var entymod in list)
                    {
                        string registrationid = entymod.android_token;
                        //PushAndroid(title, content, registrationid);//激光推送
                        //Thread.Sleep(1000);
                        AddPush(mod, entymod.account_id);

                    }

                    var listIOS = androidService.GetCompanyidIOSToken((int)mod.company_id);
                    foreach (var entymod in listIOS)
                    {
                        string registrationid = entymod.ios_token;
                        //PushAndroid(title, content, registrationid);//激光推送
                        //Thread.Sleep(1000);
                        AddPush(mod, entymod.account_id);

                    }
                }

            }
            resultmod.InitResultState(StateEnum.Success);
            return resultmod;
        }


        public void AddPush(wuliu_bid_base mod, int account_id)
        {
            wuliu_compush_base compushmod = new wuliu_compush_base();
            compushmod.account_id =account_id;
            compushmod.bid_id = mod.bid_id;
          
            string pushcontent = mod.bid_no + "&&1&&有一条到" + mod.end_city_name + "的新标单，请点击报价。";
            compushmod.content = pushcontent;
            compushmod.state = 1;
            compushmod.type = 1;
            compushmod.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
            compushmod.push_time = DateConvert.DateTimeToStamp(DateTime.Now);//推送时间需要计算保存

            var pushid = compushService.AddCompushBase(compushmod);

            wuliu_compush_base_momory compushbase = new wuliu_compush_base_momory();
            compushbase.push_id = pushid;
            compushbase.account_id = account_id;
            compushbase.state = 1;
            compushbase.type = 10;
            compushbase.content = pushcontent;
            var momoryid = compushService.AddCompushBaseMomory(compushbase);

        }



        /// <summary>
        /// 竟标结束(流标注：小于设置的最小报价人数进行流标，以及大于设置金额进行流标)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ResponseModel GetAutoEndBillList()
        {
            var resultmod = new ResponseModel();
            int timenum = DateConvert.DateTimeToStamp(DateTime.Now);
            var bidlist = bidService.GetAutoEndBidList(timenum);
            resultmod.InitResultState(StateEnum.Error);
            foreach (wuliu_bid_base mod in bidlist)
            {
                if(IsFlowBill(mod))
                {
                    resultmod.mod = bidService.UpdateDelFlag((int)mod.bid_id, 20);//进行流标操作
                    resultmod.InitResultState(StateEnum.Success);
                }
                else
                {
                    if(!AutoChooseBill(mod))
                    {
                        wuliu_bid_base enty = new wuliu_bid_base();
                        enty.state = 20;
                        enty.bid_id = mod.bid_id;
                        bidService.BidBaseUpdate(enty);
                        resultmod.InitResultState(StateEnum.Success);
                    }
                   
                }
            }
            
            return resultmod;
        }

        /// <summary>
        /// 把符合流标的数据进行流标操作
        /// </summary>
        /// <returns></returns>
        public bool IsFlowBill(wuliu_bid_base mod)
        {
            var picelist = piceservice.GetBillPriceList((int)mod.bid_id);
            if (mod.bid_minnum > 0)
            {
                if(mod.bid_minnum>picelist.Count())
                {
                    return true;
                }
            }
            var enty = picelist.FirstOrDefault();
            if (enty != null)
            {
                if (enty.final_price > mod.flownum_max)
                {

                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 到时候自动选标操作
        /// </summary>
        /// <returns></returns>
        public bool AutoChooseBill(wuliu_bid_base mod)
        {
            if(mod.bid_sel==1)
            {
                var list = piceservice.GetRePriceList((int)mod.bid_id);
                if (list != null)
                {
                    var choosemod = list.FirstOrDefault();
                    BidPriceController dal = new BidPriceController();
                    var responseModel = new ResponseModel(); BidBaseService bidbase = new BidBaseService();
                    try
                    {
                        var bidmod = bidbase.GetBid((int)choosemod.bid_id);
                        var pricemod = piceservice.GetPriceBid(choosemod.bid_wl_id);
                        var newLoad = new wuliu_bid_load();
                        newLoad.load_no = NoBuilder.GetLoadNo();
                        newLoad.load_remark = "";
                        newLoad.load_state = "1";//
                        newLoad.load_time = DateTime.Now;
                        newLoad.Operator = "自动选标";
                        newLoad.order_num = bidmod.number;
                       
                        newLoad.receipt_time = (int)bidmod.receipt_time;
                        newLoad.start_address = bidmod.start_address;
                        newLoad.start_bid_time = (int)bidmod.start_bid_time;
                        newLoad.start_city_id = bidmod.start_city_id;
                        newLoad.start_city_name = bidmod.start_city_name;
                        newLoad.wuliu_id = pricemod.wuliu_id;
                        newLoad.wuliu_name = pricemod.wuliu_name;
                        newLoad.wuliu_no = pricemod.wuliu_no;
                        newLoad.wuliu_bid_state = "10";
                        newLoad.bid_flag = "1";
                        newLoad.bid_id = bidmod.bid_id;
                        newLoad.bid_no = bidmod.bid_no;
                        newLoad.tax = pricemod.tax;
                        newLoad.price = pricemod.final_price;
                        newLoad.tax_price = pricemod.tax_price;
                        newLoad.bid_state = 1;//
                        newLoad.company_name = bidmod.company_name;
                        newLoad.company_no = bidmod.company_no;
                        newLoad.consignee_time = (int)bidmod.consignee_time;
                        newLoad.end_address = bidmod.end_address;
                        newLoad.end_address2 = bidmod.end_address2;
                        newLoad.end_bid_time = (int)bidmod.end_bid_time;
                        newLoad.end_city_id = bidmod.end_city_id;
                        newLoad.end_city_id2 = bidmod.end_city_id2;
                        newLoad.end_city_name = bidmod.end_city_name;
                        newLoad.end_city_name2 = bidmod.end_city_name2;
                        var en = piceservice.ChoiceBidPirce((int)choosemod.bid_id, choosemod.bid_wl_id,pricemod, newLoad);
                        responseModel.mod = en;
                        if (en)
                        {
                            #region 手机推送

                            string title = "", content = "", registrationid = "";

                            
                            var phonelist = androidService.GetAndroidToken((int)pricemod.wuliu_id);

                            foreach (var smsmod in phonelist)
                            {
                                try
                                {

                                    content = bidmod.bid_no + "&&5&&尊敬的企运宝用户，恭喜您，您参与订单号为" + bidmod.bid_no + "的订单竞标成功！请尽快和发货方取得联系并安排出车，祝您一帆风顺。";

                                    wuliu_compush_base compushmod = new wuliu_compush_base();
                                    compushmod.account_id = smsmod.account_id;
                                    compushmod.bid_id = bidmod.bid_id;
                                    DateTime pick = DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-1);
                                    //string pushcontent = bidmod.bid_no + "&&" + bidmod.state + "&&请" + pick.ToString("hh:mm:00") + "到" + bidmod.end_city_name + "的" + bidmod.company_name + "取货，剩余取货时间1小时，订单号" + bidmod.bid_no + "，请尽快安排出车，祝您一帆风顺。";
                                    compushmod.content = content;
                                    compushmod.state = 1;
                                    compushmod.type = 10;
                                    compushmod.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                                    compushmod.push_time = DateConvert.DateTimeToStamp(DateTime.Now);//推送时间需要计算保存

                                    var pushid = compushService.AddCompushBase(compushmod);

                                    wuliu_compush_base_momory compushbase = new wuliu_compush_base_momory();
                                    compushbase.push_id = pushid;
                                    compushbase.account_id = smsmod.account_id;
                                    compushbase.state = 1;
                                    compushbase.type = 10;
                                    compushbase.content = content;
                                    var momoryid = compushService.AddCompushBaseMomory(compushbase);

                                    registrationid = smsmod.android_token;
                                    //PushAndroid(title, content, bidmod.bid_no, registrationid);//激光推送

                                    //Thread.Sleep(1000);
                                    wuliu_compush_base compushmods = new wuliu_compush_base();
                                    compushmods.account_id = smsmod.account_id;
                                    compushmods.bid_id = bidmod.bid_id;
                                    DateTime picks = DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-1);
                                    string pushcontent = bidmod.bid_no + "&&5&&请" + picks.ToString("HH:mm:00") + "到" + bidmod.end_city_name + "的" + bidmod.end_address + "取货，剩余取货时间1小时，订单号" + bidmod.bid_no + "，请尽快安排出车，祝您一帆风顺。";
                                    compushmods.content = pushcontent;
                                    compushmods.state = 1;
                                    compushmods.type = 10;
                                    compushmods.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                                    compushmods.push_time = DateConvert.DateTimeToStamp(DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-1));//推送时间需要计算保存

                                    var pushids = compushService.AddCompushBase(compushmods);

                                    wuliu_compush_base_momory compushbases = new wuliu_compush_base_momory();
                                    compushbases.push_id = pushid;
                                    compushbases.account_id = smsmod.account_id;
                                    compushbases.state = 1;
                                    compushbases.type = 10;
                                    compushbases.content = pushcontent;
                                    var momoryids = compushService.AddCompushBaseMomory(compushbases);

                                    wuliu_compush_base compushmod2 = new wuliu_compush_base();
                                    compushmod2.account_id = smsmod.account_id;
                                    compushmod2.bid_id = bidmod.bid_id;
                                    DateTime pick2 = DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-0.5);
                                    string pushcontent2 = bidmod.bid_no + "&&5&&请" + pick2.ToString("HH:mm:00") + "到" + bidmod.end_city_name + "的" + bidmod.end_address + "取货，剩余取货时间半小时，订单号" + bidmod.bid_no + "，请尽快安排出车，祝您一帆风顺。";
                                    compushmod2.content = pushcontent2;
                                    compushmod2.state = 1;
                                    compushmod2.type = 10;
                                    compushmod2.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                                    compushmod2.push_time = DateConvert.DateTimeToStamp(DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-1));//推送时间需要计算保存
                                    var pushid2 = compushService.AddCompushBase(compushmod2);

                                    wuliu_compush_base_momory compushbase2 = new wuliu_compush_base_momory();
                                    compushbase2.push_id = pushid2;
                                    compushbase2.account_id = smsmod.account_id;
                                    compushbase2.state = 1;
                                    compushbase2.type = 10;
                                    compushbase2.content = pushcontent;
                                    var momoryid2 = compushService.AddCompushBaseMomory(compushbase2);
                                }
                                catch
                                {

                                }
                            }

                            var IOSlist = androidService.GetIOSToken((int)pricemod.wuliu_id);

                            foreach (var smsmod in IOSlist)
                            {
                                try
                                {

                                    content = bidmod.bid_no + "&&5&&尊敬的企运宝用户，恭喜您，您参与订单号为" + bidmod.bid_no + "的订单竞标成功！请尽快和发货方取得联系并安排出车，祝您一帆风顺。";

                                    wuliu_compush_base compushmod = new wuliu_compush_base();
                                    compushmod.account_id = smsmod.account_id;
                                    compushmod.bid_id = bidmod.bid_id;
                                    DateTime pick = DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-1);
                                    //string pushcontent = bidmod.bid_no + "&&" + bidmod.state + "&&请" + pick.ToString("hh:mm:00") + "到" + bidmod.end_city_name + "的" + bidmod.company_name + "取货，剩余取货时间1小时，订单号" + bidmod.bid_no + "，请尽快安排出车，祝您一帆风顺。";
                                    compushmod.content = content;
                                    compushmod.state = 1;
                                    compushmod.type = 10;
                                    compushmod.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                                    compushmod.push_time = DateConvert.DateTimeToStamp(DateTime.Now);//推送时间需要计算保存

                                    var pushid = compushService.AddCompushBase(compushmod);

                                    wuliu_compush_base_momory compushbase = new wuliu_compush_base_momory();
                                    compushbase.push_id = pushid;
                                    compushbase.account_id = smsmod.account_id;
                                    compushbase.state = 1;
                                    compushbase.type = 10;
                                    compushbase.content = content;
                                    var momoryid = compushService.AddCompushBaseMomory(compushbase);



                                    registrationid = smsmod.ios_token;
                                    //PushAndroid(title, content, bidmod.bid_no, registrationid);//激光推送

                                    //Thread.Sleep(1000);
                                    wuliu_compush_base compushmods = new wuliu_compush_base();
                                    compushmods.account_id = smsmod.account_id;
                                    compushmods.bid_id = bidmod.bid_id;
                                    DateTime picks = DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-1);
                                    string pushcontent = bidmod.bid_no + "&&5&&请" + picks.ToString("HH:mm:00") + "到" + bidmod.end_city_name + "的" + bidmod.end_address + "取货，剩余取货时间1小时，订单号" + bidmod.bid_no + "，请尽快安排出车，祝您一帆风顺。";
                                    compushmods.content = pushcontent;
                                    compushmods.state = 1;
                                    compushmods.type = 10;
                                    compushmods.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                                    compushmods.push_time = DateConvert.DateTimeToStamp(DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-1));//推送时间需要计算保存

                                    var pushids = compushService.AddCompushBase(compushmods);

                                    wuliu_compush_base_momory compushbases = new wuliu_compush_base_momory();
                                    compushbases.push_id = pushid;
                                    compushbases.account_id = smsmod.account_id;
                                    compushbases.state = 1;
                                    compushbases.type = 10;
                                    compushbases.content = pushcontent;
                                    var momoryids = compushService.AddCompushBaseMomory(compushbases);

                                    wuliu_compush_base compushmod2 = new wuliu_compush_base();
                                    compushmod2.account_id = smsmod.account_id;
                                    compushmod2.bid_id = bidmod.bid_id;
                                    DateTime pick2 = DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-0.5);
                                    string pushcontent2 = bidmod.bid_no + "&&5&&请" + pick2.ToString("HH:mm:00") + "到" + bidmod.end_city_name + "的" + bidmod.end_address + "取货，剩余取货时间半小时，订单号" + bidmod.bid_no + "，请尽快安排出车，祝您一帆风顺。";
                                    compushmod2.content = pushcontent2;
                                    compushmod2.state = 1;
                                    compushmod2.type = 10;
                                    compushmod2.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                                    compushmod2.push_time = DateConvert.DateTimeToStamp(DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-1));//推送时间需要计算保存
                                    var pushid2 = compushService.AddCompushBase(compushmod2);

                                    wuliu_compush_base_momory compushbase2 = new wuliu_compush_base_momory();
                                    compushbase2.push_id = pushid2;
                                    compushbase2.account_id = smsmod.account_id;
                                    compushbase2.state = 1;
                                    compushbase2.type = 10;
                                    compushbase2.content = pushcontent;
                                    var momoryid2 = compushService.AddCompushBaseMomory(compushbase2);
                                }
                                catch
                                {

                                }


                            }
                            #endregion
                        }
                        responseModel.InitResultState(StateEnum.Success);
                    }
                    catch (Exception ex)
                    {
                        responseModel.InitResultState(ex);
                    }

                    if (responseModel.recode == "0000")
                        return true;
                }
            }
            
            return false;
        }


        /// <summary>
        /// 激光推送
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public bool PhonePush(string str)
        {
            string content = "尊敬的企运宝用户，恭喜您，您参与订单号为" + str + "的订单竞标成功！请尽快和发货方取得联系并安排出车，祝您一帆风顺。";
            JPushClient client = new JPushClient("85a8af5b452b225ad7eb6df7", "fc03a0cfc061493602d0eff5");
            PushPayload payload = PushObject_All_All_Alert(content);
            try
            {
                var result = client.SendPush(payload);
                //由于统计数据并非非是即时的,所以等待一小段时间再执行下面的获取结果方法
                System.Threading.Thread.Sleep(10000);
                /*如需查询上次推送结果执行下面的代码*/
                var apiResult = client.getReceivedApi(result.msg_id.ToString());
                var apiResultv3 = client.getReceivedApi_v3(result.msg_id.ToString());
                /*如需查询某个messageid的推送结果执行下面的代码*/
                var queryResultWithV2 = client.getReceivedApi("1739302794");
                var querResultWithV3 = client.getReceivedApi_v3("1739302794");
                return result.isResultOK();
            }
            catch (Exception e)
            {

            }
            return false;
        }

        public static PushPayload PushObject_All_All_Alert(string ALERT)
        {
            PushPayload pushPayload = new PushPayload();
            pushPayload.platform = Platform.all();
            pushPayload.audience = Audience.all();
            pushPayload.notification = new Notification().setAlert(ALERT);
            return pushPayload;
        }
    }
}